package com.gdip.common;

import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

public class AppJwtUtil {

    // TOKEN的有效期一天（S）
    private static final int TOKEN_TIME_OUT = 3_600;
    // 加密KEY
    private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
    // 最小刷新间隔(S)
    private static final int REFRESH_TIME = 300;

    // 生产ID
    public static String getToken(Long id){
        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("id",id);
        long currentTime = System.currentTimeMillis();
        return Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date(currentTime))  //签发时间
                .setSubject("system")  //说明
                .setIssuer("hangfook") //签发者信息
                .setAudience("app")  //接收用户
                .compressWith(CompressionCodecs.GZIP)  //数据压缩方式
                .signWith(SignatureAlgorithm.HS512, generalKey()) //加密方式
                .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000*24))  //过期时间戳
                .addClaims(claimMaps) //cla信息
                .compact();
    }

    /**
     * 获取token中的claims信息
     *
     * @param token
     * @return
     */
    private static Jws<Claims> getJws(String token) {
            return Jwts.parser()
                    .setSigningKey(generalKey())
                    .parseClaimsJws(token);

    }

    /**
     * 获取payload body信息
     *
     * @param token
     * @return
     */
    public static Claims getClaimsBody(String token) {
        try {
            return getJws(token).getBody();
        }catch (ExpiredJwtException e){
            return null;
        }
    }

    /**
     * 获取hearder body信息
     *
     * @param token
     * @return
     */
    public static JwsHeader getHeaderBody(String token) {
        return getJws(token).getHeader();
    }

    /**
     * 是否过期
     *
     * @param claims
     * @return -1：有效，0：有效，1：过期，2：过期
     */
    public static int verifyToken(Claims claims) {
        if(claims==null){
            return 1;
        }
        try {
            claims.getExpiration()
                    .before(new Date());
            // 需要自动刷新TOKEN
            if((claims.getExpiration().getTime()-System.currentTimeMillis())>REFRESH_TIME*100){
                return -1;
            }else {
                return 0;
            }
        } catch (ExpiredJwtException ex) {
            return 1;
        }catch (Exception e){
            return 2;
        }
    }

    public static Boolean verify(String token){
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i == -1){
            return true;
        }else if (i == 0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    public static void main(String[] args) {
       /* Map map = new HashMap();
        map.put("id","11");*/
//        System.out.println(AppJwtUtil.getToken(1102L));
//        Jws<Claims> jws = AppJwtUtil.getJws("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAC2L0QqDMAwA_yXPFkw6a-LfxDawDoRCK2yM_bsR9nbHcV94jQobRGHKO-UwG1F4mEkQ1hJy4ZjKWjRyggmqDtgwIQuvssgE_dz97p8-7Lh7765Pq4e66VnctDVne7f_KbjcZ_WGONPvAsM25luDAAAA._HLSpxHpSl4KZbYtSx1xnyeaRpsJTQ5xz6wMfFehqUr5etW6pOhCuP4EdrhSBefJZ5evmfYcUAj_dbHkLVdxSQ");
//        Claims claims = jws.getBody();
//        int i1 = AppJwtUtil.verifyToken(AppJwtUtil.getClaimsBody("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAA_zWLQQ7CIBBF7zLrksDAMNDbTC0qGi0JNNEY7-504e7_9_I-cBsVZmCKKLgkwyV7EzIFk09ExmYOJXq7BkSYoMqA2bF1KSEjTdD3Rev-7qM8Dt-73qs8L-dtuyuQfVUgrekur_aPoz_iqs45i98fwtTjYYYAAAA.ZNc3srKZDikJ5Mcwl-JLXLClWDrT_7C-baAgM87QIQO0XYRlpvJfuo55SmyLlFwo9pPey5hcu-Xbg38vrJjyqA"));
//        int i = AppJwtUtil.verifyToken(claims);
//        System.out.println(i1);
//        System.out.println(claims.get("id"));
        /*Date date = new Date(20000000000000L);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        System.out.println(format);*/
        // 替换下面的数字为你想要生成令牌的用户ID
        Long userId = 1733139738598166529L;

        // 调用 getToken 方法生成令牌
        String token = AppJwtUtil.getToken(userId);


        // 打印生成的令牌
        System.out.println("Generated Token: " + token);
//        System.out.println(getJws("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAA_zWLSw4CIRAF79LrIeE3TffcpgmgaHRImEk0xrsLC3ev6qU-cDsqbEAppijIqkjRyusQFTkUZa1HYkso2cMCVQ7YTNAWvXFEC_Qzjrq_-5Ef8-994FWel7Lv9yHkTENIa2PnV_vHnmdc02TnjOPgaGUyiKvl7w8Q8C-klQAAAA.T6J25TH64rvp-D-7ZLWdKth2XyRQ30BMOhNpSUT_5ZUPqZ3KxQ_FEnbIq4BWNCXXw87TkdEGs7bRTbuEwbSL3g"));
//        System.out.println(getClaimsBody("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAA_zWLSw7CMAwF7-J1Izmf1klv4zYpBASN5FQCIe6Ou2D33ozmA7deYQY3MuU1oElbGE2YYjRpZW8Y3ZKRki2EMEDlDrMldJPzFHEAORat5S29PE4vovfKz8u273cFfGQF3Jru8mr_mPwZV3XWovv-AAvz6_KGAAAA.0ImyYysCkuMTfi6E91-S30fUTLfh3rB9EjevZTwvioSLCd8Js13xxQ1TNanFZATb76ZznrCDTnVLhIpfXnWmvA").get("id"));
    }

}
